package com.thinkingcoder.tcmq.server;

import java.util.List;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.thinkingcoder.tcmq.core.model.Message;
import com.thinkingcoder.tcmq.core.model.Result;
import com.thinkingcoder.tcmq.core.model.Stat;
import com.thinkingcoder.tcmq.core.model.Subscription;

/**
 * MQ Server.
 */
@RestController
@RequestMapping("/tcmq")
public class MQServer {

    // autoCreateTopic
    @RequestMapping("/autoCreateTopic")
    public Result autoCreateTopic(@RequestParam("t") String topic,
        @RequestParam(name = "aac", defaultValue = "false") boolean allowAutoCreate) {
        MessageQueue.autoCreateTopic(topic, allowAutoCreate);
        return Result.ok();
    }

    // send
    @RequestMapping("/send")
    public Result send(@RequestParam("t") String topic, @RequestBody Message<String> message) {
        return Result.ok("" + MessageQueue.send(topic, message));
    }

    // receive
    @RequestMapping("/receive")
    public Result<Message<?>> receive(@RequestParam("t") String topic, @RequestParam("cid") String consumerId) {
        return Result.message(MessageQueue.receive(topic, consumerId));
    }

    // batch
    @RequestMapping("/batch")
    public Result<List<Message<?>>> batch(@RequestParam("t") String topic, @RequestParam("cid") String consumerId,
        @RequestParam(name = "size", required = false, defaultValue = "1000") int size) {
        return Result.message(MessageQueue.batch(topic, consumerId, size));
    }

    // ack
    @RequestMapping("/ack")
    public Result<String> ack(@RequestParam("t") String topic, @RequestParam("cid") String consumerId,
        @RequestParam("offset") Integer offset) {
        return Result.ok("" + MessageQueue.ack(topic, consumerId, offset));
    }

    // subscribe
    @RequestMapping("/subscribe")
    public Result<String> subscribe(@RequestParam("t") String topic, @RequestParam("cid") String consumerId) {
        MessageQueue.subscribe(new Subscription(topic, consumerId, -1));
        return Result.ok();
    }

    // unsubscribe
    @RequestMapping("/unSubscribe")
    public Result<String> unSubscribe(@RequestParam("t") String topic, @RequestParam("cid") String consumerId) {
        MessageQueue.unSubscribe(new Subscription(topic, consumerId, -1));
        return Result.ok();
    }

    @RequestMapping("/stat")
    public Result<Stat> stat(@RequestParam("t") String topic, @RequestParam("cid") String consumerId) {
        return Result.stat(MessageQueue.stat(topic, consumerId));
    }
}
